package com.ruoyi.web.controller.fx;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.CodeGeneratorUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.domain.fx.FxSupplierGood;
import com.ruoyi.system.service.fx.IFxChinaService;
import com.ruoyi.system.service.fx.IFxSupplierGoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 供应商商品Controller
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@RestController
@RequestMapping("/fx/supplier/good")
public class FxSupplierGoodController extends BaseController {
    @Autowired
    private IFxSupplierGoodService fxSupplierGoodService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private IFxChinaService fxChinaService;

    /**
     * 查询供应商商品列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FxSupplierGood fxSupplierGood) {
//        startPage();
        List<FxSupplierGood> list = fxSupplierGoodService.selectFxSupplierGoodList(fxSupplierGood);
        List<Long> ids = list.stream().map(FxSupplierGood::getId).collect(Collectors.toList());
        if(!ids.isEmpty()){
            fxSupplierGood.setGoodIds(ids.toArray(new Long[ids.size()]));
            List<FxSupplierGood> goodList = fxSupplierGoodService.selectFxSupplierSonGoodList(fxSupplierGood);
            list.addAll(goodList);
        }
        list.forEach(good -> {
            Long[] regionArr = Convert.toLongArray(",",good.getRegion());
            String regionStr =fxChinaService.selectRegionNameByIds(regionArr);
            if (StringUtils.isNotBlank(regionStr))
                good.setRegionName(regionStr);
            if (StringUtils.isNotEmpty(good.getSpecifications())) {
                String[] goodArr = good.getSpecifications().split(";");
                good.setSpecificationsList(Arrays.asList(goodArr));
            }
        });
        return getDataTable(list);
    }


    /**
     * 查询供应商商品列表
     */
    @GetMapping("/getGoodsList")
    public TableDataInfo getGoodsList(FxSupplierGood fxSupplierGood) {
//        startPage();
        List<FxSupplierGood> list = fxSupplierGoodService.selectFxSupplierGoodList(fxSupplierGood);
        list.forEach(good -> {
            Long[] regionArr = Convert.toLongArray(",",good.getRegion());
            String regionStr =fxChinaService.selectRegionNameByIds(regionArr);
            if (StringUtils.isNotBlank(regionStr))
                good.setRegionName(regionStr);
            if (StringUtils.isNotEmpty(good.getSpecifications())) {
                String[] goodArr = good.getSpecifications().split(";");
                good.setSpecificationsList(Arrays.asList(goodArr));
            }
        });
        return getDataTable(list);
    }


    /**
     * 查询供应商商品列表
     */
    @GetMapping("/listByClassify")
    public TableDataInfo listByClassify(FxSupplierGood fxSupplierGood) {
        // startPage();
       // List<FxSupplierGood> list = fxSupplierGoodService.selectFxSupplierGoodList(fxSupplierGood);
        List<FxSupplierGood> list = fxSupplierGoodService.selectFxStoreSupplierGoodList(fxSupplierGood);
        return getDataTable(list);
    }



    /**
     * 导出供应商商品列表
     */
    @Log(title = "供应商商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FxSupplierGood fxSupplierGood) {
        List<FxSupplierGood> list = fxSupplierGoodService.selectFxSupplierGoodList(fxSupplierGood);
        ExcelUtil<FxSupplierGood> util = new ExcelUtil<FxSupplierGood>(FxSupplierGood.class);
        util.exportExcel(response, list, "供应商商品数据");
    }

    /**
     * 获取供应商商品详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(fxSupplierGoodService.selectFxSupplierGoodById(id));
    }

    /**
     * 新增供应商商品
     */
    @Log(title = "供应商商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FxSupplierGood fxSupplierGood) {
        return toAjax(fxSupplierGoodService.insertFxSupplierGood(fxSupplierGood));
    }

    /**
     * 修改供应商商品
     */
    @Log(title = "供应商商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FxSupplierGood fxSupplierGood) {
        return toAjax(fxSupplierGoodService.updateFxSupplierGood(fxSupplierGood));
    }

    /**
     * 补货
     * @param fxSupplierGood 参数
     * @return
     */
    @PostMapping("/replenishment")
    public AjaxResult replenishment(@RequestBody FxSupplierGood fxSupplierGood) {
        return toAjax(fxSupplierGoodService.updateFxSupplierCounts(fxSupplierGood));
    }

    /**
     * 删除供应商商品
     */
    @Log(title = "供应商商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(fxSupplierGoodService.updateDelFlag(ids));
    }

    /**
     * 创建一维码（生成条形码）
     *
     * @param ids
     * @return
     */
    @PostMapping("/generateBarCode")
    public AjaxResult generateBarCode(Long[] ids) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        // 将日期格式化为指定格式的字符串
        String formattedDate = currentDate.format(formatter);
        int width = 400;// 条形码宽度
        int height = 100;// 条形码高度
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath() + "/barCode/" + formattedDate;
//        String filePath = "/www/wwwroot/fx/java/D:/ruoyi/uploadPath/barCode/"+formattedDate;// 条形码存放路径
        String imgUrl = null;
        for (Long id : ids) {
            String data = id.toString();// 内容
            imgUrl = CodeGeneratorUtil.generateBarCode(data, width, height, filePath);
//            String url = serverConfig.getUrl() + "/profile/upload/barCode/" + formattedDate + imgUrl;
            String url = "/profile/upload/barCode/" + formattedDate + imgUrl;
            FxSupplierGood fxSupplierGood = new FxSupplierGood();
            fxSupplierGood.setId(id);
            fxSupplierGood.setQrCodeUrl(url);
            fxSupplierGoodService.updateFxSupplierGood(fxSupplierGood);
        }
        return AjaxResult.success(imgUrl);
    }
}
